package com.last1mile.web.control;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.last1mile.commons.ReserveStatusEnum;
import com.last1mile.model.Login;
import com.last1mile.model.Reserve;
import com.last1mile.model.ReserveView;
import com.last1mile.pojo.MerServeDO;
import com.last1mile.pojo.ServeReserveDO;
import com.last1mile.pojo.UserDO;
import com.last1mile.service.ReserveService;
import com.last1mile.service.ServeService;
import com.last1mile.service.UserService;

@Controller
@RequestMapping("/r/*")
@SessionAttributes("currentLogin")
public class ReserveController {
    @Autowired
    @Qualifier("serveServiceImpl")
    ServeService   serveService;
    
    @Autowired
    @Qualifier("userServiceImpl")
    UserService    userService;
    
    @Autowired
    @Qualifier("reserveServiceImpl")
    ReserveService   reserveService;
    
    /**
     * 预约日历初始化
     * @param serveId
     * @param login
     * @param model
     * @return
     */
    @RequestMapping(value = "/reserveCalendar-{serveId}.html", method = RequestMethod.GET)
    public String reserveCalendar(@PathVariable Integer serveId,@ModelAttribute("currentLogin") Login login, ModelMap model){
        Calendar cal = Calendar.getInstance();
        Date today = new Date();
        cal.setTime(today);
        cal.set(Calendar.DATE, 1);//设为当前月的1号
        Date firstDayOfMonth = cal.getTime();
        cal.add(Calendar.MONTH, 1);//加1个月，变成下月的1号
        cal.add(Calendar.DATE, -1);//减去一天，变成当月最后一天
        Date lastDayOfMonth = cal.getTime();
        
        List<ReserveView> reserveViewList = new ArrayList<ReserveView>();
        //  不管当前登录者是买家还是卖家看到的预约日历是一样的。这个月内对某服务的所有的预约
        List<ServeReserveDO> reserveList = this.reserveService.queryServeReserve(serveId, firstDayOfMonth, lastDayOfMonth);
        for(ServeReserveDO reserveDo:reserveList){
            ReserveView rv = new ReserveView();
            rv.setReserveDo(reserveDo);
            rv.setPerName(login.getLoginId());
            reserveViewList.add(rv);
        }
        model.addAttribute("reserveViewList", reserveViewList);
        
        // 当前登陆者
        UserDO currntLoginUser = this.userService.queryUserById(login.getUserId());
        // 服务
        MerServeDO serve = this.serveService.queryServeById(serveId);
        
        String serveTitle = serve.getServeTitle()+" "+ currntLoginUser.getSurname()+" "+currntLoginUser.getLastname();
        model.addAttribute("serveTitle", serveTitle);
        model.addAttribute("merId", serve.getMerId());
        model.addAttribute("serveId", serveId);
        model.addAttribute("perId", login.getUserId());
        
        boolean isCurrntLoginUserPer = true;
        //IMPORTANT: 该登陆者经过判断如果是买家，买家才能发起对卖家服务的预约。如果是卖家，则不可以发起对自己服务的预约。
        if(login.getUserId().compareTo(serve.getMerId()) == 0){
        	isCurrntLoginUserPer = false;
        }else{
        	isCurrntLoginUserPer = true;
        }
        model.addAttribute("isCurrntLoginUserPer", isCurrntLoginUserPer);
        
        DateFormat formater = new SimpleDateFormat("yyyy-MM-dd",Locale.US);
        model.addAttribute("today", formater.format(today));
        model.addAttribute("firstDayOfMonth", formater.format(firstDayOfMonth));
        model.addAttribute("lastDayOfMonth", formater.format(lastDayOfMonth));
        return "serve/ReserveCalendar";
    }
    
    /**
     * 预约detail
     * @param reserveId
     * @param login
     * @param model
     * @return
     */
    @RequestMapping(value = "/reserveDetail-{reserveId}.html", method = RequestMethod.GET)
    public String reserveDetail(@PathVariable Integer reserveId, @ModelAttribute("currentLogin") Login login, ModelMap model) {
        ServeReserveDO reserveDo = this.reserveService.queryReserveById(reserveId);
        model.addAttribute("reserve", reserveDo);
        
        MerServeDO serve = this.serveService.queryServeById(reserveDo.getMerServeId());
        model.addAttribute("serve", serve);

        //当前登陆者是否是买家
        boolean isCurrntLoginUserPer = true;
        if(login.getUserId().compareTo(serve.getMerId()) == 0){
            isCurrntLoginUserPer = false;
        }else{
            isCurrntLoginUserPer = true;
        }
        model.addAttribute("isCurrntLoginUserPer", isCurrntLoginUserPer);
        
        UserDO merUser = this.userService.queryUserById(reserveDo.getMerId());
        model.addAttribute("merUser", merUser);
        
        return "serve/ReserveDetailForm";
    }
    
    @RequestMapping(value = "/refuseReserve-{reserveId}.html", method = RequestMethod.GET)
    public String refuseReserve(@PathVariable Integer reserveId, @ModelAttribute("currentLogin") Login login, ModelMap model){
        this.reserveService.updateReserveStatus(reserveId, ReserveStatusEnum.REFUSE);
        
        ServeReserveDO reserveDo = this.reserveService.queryReserveById(reserveId);
        model.addAttribute("reserve", reserveDo);
        
        MerServeDO serve = this.serveService.queryServeById(reserveDo.getMerServeId());
        model.addAttribute("serve", serve);

        //当前登陆者是否是买家
        boolean isCurrntLoginUserPer = true;
        if(login.getUserId().compareTo(serve.getMerId()) == 0){
            isCurrntLoginUserPer = false;
        }else{
            isCurrntLoginUserPer = true;
        }
        model.addAttribute("isCurrntLoginUserPer", isCurrntLoginUserPer);
        
        UserDO merUser = this.userService.queryUserById(reserveDo.getMerId());
        model.addAttribute("merUser", merUser);
        
        return "serve/ReserveDetailForm";
    }
    
    @RequestMapping(value = "/confirmReserve-{reserveId}.html", method = RequestMethod.GET)
    public String confirmReserve(@PathVariable Integer reserveId, @ModelAttribute("currentLogin") Login login, ModelMap model){
        this.reserveService.updateReserveStatus(reserveId, ReserveStatusEnum.CONFIRM);
        
        ServeReserveDO reserveDo = this.reserveService.queryReserveById(reserveId);
        model.addAttribute("reserve", reserveDo);
        
        MerServeDO serve = this.serveService.queryServeById(reserveDo.getMerServeId());
        model.addAttribute("serve", serve);

        //当前登陆者是否是买家
        boolean isCurrntLoginUserPer = true;
        if(login.getUserId().compareTo(serve.getMerId()) == 0){
            isCurrntLoginUserPer = false;
        }else{
            isCurrntLoginUserPer = true;
        }
        model.addAttribute("isCurrntLoginUserPer", isCurrntLoginUserPer);
        
        UserDO merUser = this.userService.queryUserById(reserveDo.getMerId());
        model.addAttribute("merUser", merUser);
        
        return "serve/ReserveDetailForm";
    }
    
    /**
     * 预约日历 drag event and drop event to the calendar 创建event
     * @param serveId
     * @param login
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = "/createReserve-{serveId}.html", method = RequestMethod.POST)
    public String createReserveSubmit(@PathVariable Integer serveId, @ModelAttribute("currentLogin") Login login,HttpServletRequest request, ModelMap model) {
        DateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.US);
        try {
            Reserve reserve = new Reserve();
            reserve.setMerId(Integer.parseInt(request.getParameter("merId")));
            reserve.setMerServeId(serveId);
            reserve.setPerId(Integer.parseInt(request.getParameter("perId")));
            
            Date beginDate = formater.parse(request.getParameter("startDateStr"));
            reserve.setBeginTime(beginDate);
            
            String allDayStr = request.getParameter("allDay");
            boolean allDay = Boolean.valueOf(allDayStr);
            reserve.setAllDay(allDay);
            
            if(allDay == false){
                Calendar cal = Calendar.getInstance();
                cal.setTime(beginDate);
                cal.add(Calendar.HOUR_OF_DAY, 2);
                Date endDate = cal.getTime();
                reserve.setEndTime(endDate);
            }else{
                reserve.setEndTime(null);
            }
            
            Integer reserveId = this.reserveService.createReserve(reserve);
            model.addAttribute("reserveId", reserveId);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        
        return "serve/ReserveServeSuccess";
    }
    
    /**
     * 预约日历 resizeEvent 和 dropEvent 后改变 event的开始结束时间
     * @param serveId
     * @param login
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = "/resizeReserveTime-{serveId}.html", method = RequestMethod.POST)
    public String resizeReserveTime(@PathVariable Integer serveId, @ModelAttribute("currentLogin") Login login,HttpServletRequest request, ModelMap model) {
        
        try {
            Integer reserveId = null;
            Date beginTime = null;
            Date endTime = null;
            Boolean allDay = null;
            
            
            
            String reserveIdStr = request.getParameter("reserveId");
            if(StringUtils.isNotBlank(reserveIdStr)){
            	reserveId = Integer.parseInt(reserveIdStr);
            }
            
            DateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.US);
            String startDateStr = request.getParameter("startDateStr");
            if(StringUtils.isNotBlank(startDateStr)){
                beginTime = formater.parse(startDateStr);
            }
            
            String endDateStr = request.getParameter("endDateStr");
            if(StringUtils.isNotBlank(endDateStr)){
                endTime = formater.parse(endDateStr);
            }
            
            String allDayStr = request.getParameter("allDay");
            if(StringUtils.isNotBlank(allDayStr)){
            	allDay = Boolean.valueOf(allDayStr);
                
                Calendar cal = Calendar.getInstance();
                cal.setTime(beginTime);
                if(allDay == true){
                    cal.set(Calendar.HOUR_OF_DAY, 0);
                    cal.set(Calendar.MINUTE, 0);
                    cal.set(Calendar.SECOND, 0);
                    beginTime = cal.getTime();
                    endTime = null;
                }else{
                    if(endTime == null){
                        cal.add(Calendar.HOUR_OF_DAY, 2);
                        endTime = cal.getTime();
                    }
                }
            }
            
            this.reserveService.updateReserveBeginEndTime(reserveId, beginTime, endTime, allDay);
            model.addAttribute("reserveId", reserveId);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        
        return "serve/ReserveServeSuccess";
    }
}
